using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerCommands, APIResult<int>>
    {
        private readonly IBaseRepository<Customer> customerRep;

        public DeleteCustomerCommandHandler(IBaseRepository<Customer> customerRep)
        {
            this.customerRep = customerRep;
        }

        public Task<APIResult<int>> Handle(DeleteCustomerCommands request, CancellationToken cancellationToken)
        {
            if (request == null || request.CustomerId <= 0)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "参数无效：CustomerId",
                    Data = 0
                });
            }

            try
            {
                // 检查是否存在且未被删除（软删除）
                var exist = customerRep.QueryFirstOrDefault<Customer>(
                    "SELECT * FROM Customer WHERE Id = @Id AND IsDeleted = false",
                    new { Id = request.CustomerId });

                if (exist == null)
                {
                    return Task.FromResult(new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "客户不存在或已删除",
                        Data = 0
                    });
                }

                // 软删除：将 IsDeleted 标记为 true
                var sql = "UPDATE Customer SET IsDeleted = true WHERE Id = @Id AND IsDeleted = false";
                var rows = customerRep.Execute(sql, new { Id = request.CustomerId });

                return Task.FromResult(new APIResult<int>
                {
                    Code = rows > 0 ? APIEnums.Success : APIEnums.Fail,
                    Msg = rows > 0 ? "删除成功" : "删除失败",
                    Data = rows
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "删除失败：" + ex.Message,
                    Data = 0
                });
            }
        }
    }
}
